import React from 'react';
import {Link} from 'react-router';
import {Icon, Message} from 'antd';
import {ADD_ORDER, PAY_ORDER} from '../../constants/userTypes';
import {FETCH_ACT_LIST_DETAIL_PERSON} from '../../constants/actTypes';
import {formatDateBetween, formatDateWithCh, setItem} from '../../utils';

/**
 * 加载公共组件
 * */
import MainSection from '../../components/MainSection/MainSection';
import Panel from '../../components/Panel/Panel';
import FootSubmitBtn from '../../components/FootSubmitBtn/FootSubmitBtn';
import WeChatConfig from '../../components/WeChatConfig/WeChatConfig';
import Price from '../../components/Price/Price';


/**
 * 加载样式或图片文件
 * */
import './sass/applyAct.scss';
import wxIcon from '../_common_img/payWay/weixin.png';
import zfbIcon from '../_common_img/payWay/zfb.png';

class ApplyAct extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.handleChooseFam = this.handleChooseFam.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
            curAct: {},
            actStatus: 2,
            curMember: [],
            curChild: [],
            curAdult: [],
            type: 101
        };
    }

    componentDidMount() {
        const {location, actions, params, user} = this.props;
        // console.log(location.state);
        if (location.state) {
            if (location.state.comeFrom === 'order') {
                // 获取当前活动
                actions.fetchActListDetailPerson(params.id).then(response => {
                    if (response.type === FETCH_ACT_LIST_DETAIL_PERSON) {
                        if (response.data.code === 20000) {
                            let curAct = response.data.data;
                            let curMember = curAct.familyIds.split(',').map(item => parseInt(item));
                            let curChild = [];
                            let curAdult = [];
                            // 如估计存了家庭成员列表 就不再发请求
                            if (user.famList && user.famList.length) {
                                let curMemberJsonArr = user.famList.filter(item => curMember.indexOf(item.id) > -1);
                                console.log(curMemberJsonArr)
                                curMemberJsonArr.map(item => {
                                    [101, 102].indexOf(item.relation) > -1 ? curChild.push(item.id) : curAdult.push(item.id);
                                });
                                this.setState({
                                    curMember: curMember,
                                    curChild: curChild,
                                    curAdult: curAdult
                                });
                            } else {
                                actions.fetchFamList().then(res => {
                                    if (res.data.code === 20000) {
                                        setTimeout(() => {
                                            let curMemberJsonArr = user.famList.filter(item => curMember.indexOf(item.id) > -1);
                                            curMemberJsonArr.map(item => {
                                                [101, 102].indexOf(item.relation) > -1 ? curChild.push(item.id) : curAdult.push(item.id);
                                            });
                                            this.setState({
                                                curMember: curMember,
                                                curChild: curChild,
                                                curAdult: curAdult
                                            });
                                        }, 100)
                                    }
                                });
                            }
                            // console.log(curChild);
                            // console.log(curAdult);
                        } else {
                            console.log(response.data.message)
                        }
                    }
                })
            } else {
                this.setState({
                    curMember: location.state.curMember,
                    curChild: location.state.curChild,
                    curAdult: location.state.curAdult
                });
            }
        }
    }

    handleChooseFam() {
        const {params} = this.props;
        this.context.router.push({
            pathname: "/userCenter/famMan",
            state: {
                backUrl: "/activityList/" + params.id + "/applyAct",
                chooseFlag: true, //成员管理里面 是否可以选择
                curMember: this.state.curMember,
                curChild: this.state.curChild,
                curAdult: this.state.curAdult
            }
        })
    }

    handleSubmit() {
        const {actions, params, act, user} = this.props;
        let isScore = act.curAct.type === 102;

        if (this.state.curChild.length < 1) {
            Message.info('至少选择一位儿童');
            return false;
        } else if (this.state.curAdult.length < 1) {
            Message.info('至少选择一位家长');
            return false;
        }
        if (isScore && (act.curAct.point * this.state.curChild.length > user.userInfo.point)) {
            Message.info('积分不足');
            return false;
        }

        let requestData = {};
        if (isScore) {
            requestData = {
                eventId: params.id,
                familyIds: this.state.curMember.join(','),
            };
            actions.payOrder(requestData).then(res => {
                if (res.type === PAY_ORDER) {
                    if (res.data.code === 20000) {
                        let orderNumber = res.data.data.number;
                        this.context.router.push({
                            pathname: "/activityList/" + params.id + "/applySuccess",
                            state: {
                                number: orderNumber,
                                eventId: params.id
                            }
                        })
                    }else{
                        Message.info(res.data.message);
                    }
                }
            });
        } else {
            requestData = {
                eventId: params.id,
                familyIds: this.state.curMember.join(','),
                method: this.state.type,
                type: 101
            };
            actions.payOrder(requestData).then(res => {
                if (res.type === PAY_ORDER) {
                    if (res.data.code === 20000) {
                        let orderNumber = res.data.data.number;
                        actions.fetchWxPaySign({
                            number: orderNumber,
                            timestamp: user.wxConfig.timestamp,
                            nonceStr: user.wxConfig.nonceStr
                        }).then(res => {
                            console.log('get payConfig');
                            if (res.data.code === 20000) {
                                let sign = res.data.data;
                                wx.chooseWXPay({
                                    appId: sign.appId, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                    timestamp: sign.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                    nonceStr: sign.nonceStr, // 支付签名随机串，不长于 32 位
                                    package: sign.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                                    signType: sign.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                    paySign: sign.paySign, // 支付签名
                                    success: function (res) {
                                        // 支付成功后的回调函数
                                    }
                                });
                                this.timer = setInterval(() => {
                                    actions.fetchPayResult({number: orderNumber}).then(res => {
                                        if (res.data.data.payStatus == 102) {
                                            console.log('finish pay');
                                            // setItem('payData', data);
                                            clearInterval(this.timer);
                                            this.context.router.push({
                                                pathname: "/activityList/" + params.id + "/applySuccess",
                                                state: {
                                                    number: orderNumber,
                                                    eventId: params.id
                                                }
                                            })
                                        }
                                    })
                                }, 1000)
                            }

                        })
                    }else{
                        Message.info(res.data.message)
                    }
                }
            });
        }
    }

    render() {
        const {actions, user, act} = this.props;
        let curAct = act.curAct;
        let submitFlag = this.state.curMember.length;
        let isScore = act.curAct.type === 102;
        return (
            <MainSection className="apply-act" title="订单支付">
                {
                    isScore ? null : <WeChatConfig actions={actions}/>
                }
                {
                    // <div className="act-header">
                    //     <img src={curAct.image+"?imageView2/1/w/200/h/200"} alt=""/>
                    //     <div>
                    //         <h5>{curAct.name}</h5>
                    //         <p>{curAct.intro}</p>
                    //     </div>
                    // </div>
                }
                <Panel title='活动信息' className="act-info">
                    <ul>
                        <li>
                            <em>活动价格</em>
                            <span className="color-6 fs20">
                                {
                                    curAct.type === 101 && <Price num={curAct.price}/>
                                }
                                {
                                    curAct.type === 102 && <Price num={curAct.point} isScore={true}/>
                                }
                                /儿童(成人免费)
                            </span>
                        </li>
                        <li>
                            <em>活动名称</em>
                            <span className="color-6">{curAct.name}</span>
                        </li>
                        <li>
                            <em>活动时间</em>
                            <span className="color-6">
                                {
                                    (curAct.startTime && curAct.endTime) ? formatDateBetween(curAct.startTime, curAct.endTime) : null
                                }
                            </span>
                        </li>
                        <li>
                            <em>活动地点</em>
                            <span className="color-6">{curAct.location}</span>
                        </li>
                    </ul>
                </Panel>
                <Panel title='参与活动的家庭成员' className="act-fam">
                    <div className="act-footer color-6" onClick={this.handleChooseFam}>
                        {
                            submitFlag ? (
                                <span>
                                    已选择
                                    <em>{this.state.curChild.length}</em>位儿童,
                                    <em>{this.state.curAdult.length}</em>位成人
                                </span>
                            ) : "请选择参与人员"
                        }
                        <Icon type="right"/>
                    </div>
                </Panel>
                {
                    isScore ? (
                        <Panel title="积分支付" className="act-score">
                            <p className="score"><em>总积分</em><span>{user.userInfo.point || 0}</span></p>
                            <p className="score">
                                <em>活动所需积分</em><span>{act.curAct.point * this.state.curChild.length}</span></p>
                        </Panel>
                    ) : (
                        <Panel title="支付方式" className="act-pay">
                            <label className="line-wrap">
                                <span><img src={wxIcon} alt=""/>微信支付</span>
                                <input type="radio" name="payType"
                                       value={101}
                                       checked={parseInt(this.state.type) === 101 ? 'checked' : ''}
                                       onChange={e => this.setState({type: e.target.value})}/>
                            </label>
                            {
                                // <label className="line-wrap no-border">
                                //     <span><img src={zfbIcon} alt=""/>支付宝支付</span>
                                //     <input type="radio" name="payType"
                                //            value={102}
                                //            checked={this.state.type == 102 ? 'checked' : ''}
                                //            onChange={e=>this.setState({type:e.target.value})}/>
                                // </label>
                            }
                        </Panel>
                    )
                }

                <FootSubmitBtn submitFlag={submitFlag}
                               price={this.state.curChild.length * parseInt(isScore ? curAct.point : curAct.price)}
                               score={isScore}
                               submitFn={this.handleSubmit} btnText="立即支付"/>
            </MainSection>
        );
    }
}

export default ApplyAct;